package xmltest;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.List;

public class Test {
    public static void main(String[] args) throws FileNotFoundException, DocumentException {
        //1.创建解析器
        SAXReader saxReader = new SAXReader();
        //2.调用read方法，传入xml文件路径
        Document read = saxReader.read(new FileReader("day14-code/src/xml/XMLDemo1.xml"));
        //3.获取xml文件根元素
        Element rootElement = read.getRootElement();
        System.out.println("根标签名称为：" + rootElement.getName());
        //4.获取根元素下的所有子元素
        List<Element> elements = rootElement.elements();
        for (Element element : elements) {
            System.out.println("\t子标签的名称为："+element.getName() + "子标签的id属性为：" + element.attributeValue("id"));
            //5.获取子元素下的属性值，并进行缩进输出
            Element name = element.element("name");
            System.out.println("\t\t孙子标签名为：" + name.getName() + "书名为：" + name.getText());

            Element author = element.element("author");
            System.out.println("\t\t孙子标签名为：" + author.getName() + "作者为：" + author.getText());

            Element price = element.element("price");
            System.out.println("\t\t孙子标签名为：" + price.getName() + "价格为：" + price.getText());
        }

    }
}
